package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency

import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentStatePagerAdapter
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.QMUIDisplayHelper
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.SHOW_BUYING_PAGE_CML
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.AgencyFragmentBinding
import com.example.shushiyunsst.fragment.main.MainFragment
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.bean.AgencyProxyIndexBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.chlid.AgencyApplyingFragment
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.chlid.AgencyCenterFragment
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.chlid.AgencyHeaderFragment
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.chlid.AgencyMySpotFragment
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.AGENCY_APPLYING_INTENT_TO_AGENCY_MY_SPOT
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.AGENCY_APPLYING_REST_ON_CHARGE
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.AGENCY_MY_SPOT_TO_APPLYING_PAGE
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.REQUIRE_REFRESH_PROXY_INDEX
import com.example.shushiyunsst.util.AGENCY
import com.example.shushiyunsst.util.HiDataBus
import com.google.android.material.appbar.AppBarLayout
import org.greenrobot.eventbus.EventBus
import kotlin.math.abs

/**
 * 代理
 * */
@Route(path = AGENCY)
class AgencyFragment : BaseDataBindingFragment<AgencyFragmentBinding>(),
    AppBarLayout.OnOffsetChangedListener {
    companion object {
        fun newInstance(): AgencyFragment {
            val args = Bundle()

            val fragment = AgencyFragment()
            fragment.arguments = args
            return fragment
        }
    }


    private val subPage = listOf<BaseFragmentEx>(
        AgencyCenterFragment.newInstance(),
        AgencyApplyingFragment.newInstance(),
        AgencyMySpotFragment.newInstance(),
    )

    private var pagerAdapter: FragmentStatePagerAdapter? = null

    private var mNavigationHeight = 1

    private var mNavigationBg: View? = null

    private var mToolbar: Toolbar? = null

    private var mTitleTextView: View? = null

    override fun layoutId() = R.layout.agency_fragment

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mNavigationBg = view.findViewById(R.id.mNavigationBg)
        mNavigationBg?.setBackgroundResource(R.color.bg_color_0)
        mToolbar = view.findViewById(R.id.mToolbar)
        mToolbar?.setTitle(R.string.new_sale_dai_li)
        mToolbar?.setTitleTextColor(ContextCompat.getColor(_mActivity, R.color.text_color_6))
        mToolbar?.setNavigationOnClickListener { onBackPressedSupport() }

        try {
            val javaClass = mToolbar?.javaClass
            val mTitleTextViewField = javaClass?.getDeclaredField("mTitleTextView")
            mTitleTextViewField?.isAccessible = true
            mTitleTextView = mTitleTextViewField?.get(mToolbar) as View
            mTitleTextView?.alpha = 0.0f
        } catch (e: Exception) {
            e.printStackTrace()
        }

        val lp = viewBinder.mBannerLayout.layoutParams

        lp.height = QMUIDisplayHelper.getScreenWidth(_mActivity) / 2

        viewBinder.mBannerLayout.layoutParams = lp

        viewBinder.mNavigation.measure(0, 0)

        mNavigationHeight = viewBinder.mNavigation.measuredHeight

        viewBinder.mHeaderView.minimumHeight = mNavigationHeight

        loadRootFragment(R.id.banner, AgencyHeaderFragment.newInstance())

        pagerAdapter = object
            :
            FragmentStatePagerAdapter(childFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

            override fun getCount() = subPage.size

            override fun getItem(position: Int) = subPage[position]

            override fun getPageTitle(position: Int): CharSequence {
                val mAgencySubPageInfo = getItem(position) as AgencySubPageInfo
                return AppGlobals.getApplication().getString(mAgencySubPageInfo.title)
            }

        }

        viewBinder.mViewPager.adapter = pagerAdapter

        viewBinder.mTabLayout.setupWithViewPager(viewBinder.mViewPager)

        viewBinder.mTabLayout.setTabIconTintResource(R.color.agency_tab_icon_tint)

        val tabCount = viewBinder.mTabLayout.tabCount

        for (i in 0 until tabCount) {
            val tab = viewBinder.mTabLayout.getTabAt(i)
            val mAgencySubPageInfo = subPage[i] as AgencySubPageInfo
            val icon =
                ContextCompat.getDrawable(_mActivity, mAgencySubPageInfo.icon)
            tab?.icon = icon
        }

        viewBinder.mAppBarLayout.addOnOffsetChangedListener(this)

        requireData()

        onEvent()

    }

    private fun requireData() {
        val proxyIndex = _mActivity.getString(R.string.proxyIndex)

        RestClient.builder()
            .url(proxyIndex)
            .success {
                val obj = JSON.parseObject(it, AgencyProxyIndexBean::class.java)
                HiDataBus.with<AgencyProxyIndexBean>(proxyIndex).postStickyData(obj)
            }
            .failure { }
            .error { _, _ -> }
            .build().post()
    }

    private fun onEvent() {

        HiDataBus.with<String>(AGENCY_APPLYING_REST_ON_CHARGE)
            .observerSticky(this, false, {
                start(MainFragment.newInstance(), SINGLETASK)
                EventBus.getDefault().post(MessageWrap.getInstance(SHOW_BUYING_PAGE_CML))
            })

        HiDataBus.with<String>(AGENCY_MY_SPOT_TO_APPLYING_PAGE)
            .observerSticky(this, false, {
                viewBinder.mViewPager.currentItem = 1
            })

        HiDataBus.with<String>(AGENCY_APPLYING_INTENT_TO_AGENCY_MY_SPOT)
            .observerSticky(this, false, {
                viewBinder.mViewPager.currentItem = 2
            })

        HiDataBus.with<String>(REQUIRE_REFRESH_PROXY_INDEX)
            .observerSticky(this, false, {
                requireData()
            })
    }

    override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
        val totalScrollRange = (appBarLayout?.totalScrollRange ?: 1)
        val alph = abs(verticalOffset * 1.0f) / totalScrollRange * 1.0f
        mNavigationBg?.alpha = alph
        mTitleTextView?.alpha = alph
//        totalScrollRange-

    }


    override fun onDestroy() {
        super.onDestroy()
        viewBinder.mAppBarLayout.removeOnOffsetChangedListener(this)
    }

    override fun onBackPressedSupport(): Boolean {
        pop()
        return true
    }


}